<?php
// 编排考场及预编排监考员 - 里程碑3：遴选课室
// 启动会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 启用错误显示
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 统一导航栏引用
require_once 'common/navigation.php';

// 数据库连接
require_once 'database.php';

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// 检查权限：仅账号角色role为"考试项目管理员"的账户可进入
$user_id = $_SESSION['user_id'];
$role_sql = "SELECT role FROM user_roles WHERE user_id = ?"; 
$stmt = $conn->prepare($role_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$role_result = $stmt->get_result();
if ($role_result->num_rows === 0 || $role_result->fetch_assoc()['role'] !== '考试项目管理员') {
    header("Location: user_home.php");
    exit();
}

// 获取考试项目ID
$exam_id = isset($_GET['exam_id']) ? intval($_GET['exam_id']) : 0;
if ($exam_id <= 0) {
    header("Location: exam_projects.php");
    exit();
}

// 获取考试项目名称
$exam_sql = "SELECT exam_name FROM exams WHERE id = ?";
$stmt = $conn->prepare($exam_sql);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$exam_result = $stmt->get_result();
if ($exam_result->num_rows === 0) {
    header("Location: exam_projects.php");
    exit();
}
$exam_info = $exam_result->fetch_assoc();
$exam_name = $exam_info['exam_name'];

// 获取所有课室信息
$rooms_sql = "SELECT * FROM examination_rooms ORDER BY building_number, floor_number, room_number";
$rooms_result = $conn->query($rooms_sql);
$all_rooms = $rooms_result->fetch_all(MYSQLI_ASSOC);

// 获取当前项目的考场信息
$arrange_sql = "SELECT * FROM arrange_examination_rooms_and_invigilators WHERE exam_id = ? ORDER BY session_number";
$stmt = $conn->prepare($arrange_sql);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$arrange_result = $stmt->get_result();
$existing_data = $arrange_result->fetch_all(MYSQLI_ASSOC);

// AJAX处理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    if ($_POST['action'] === 'select_rooms') {
        // 遴选课室逻辑
        $session_id = intval($_POST['session_id']);
        $room_type = $_POST['room_type'];
        $required_rooms = intval($_POST['required_rooms']);
        $backup_rooms = intval($_POST['backup_rooms']);
        
        // 1. 匹配符合要求的课室
        $matching_rooms = [];
        foreach ($all_rooms as $room) {
            if ($room['room_type'] === $room_type && $room['purpose'] === '考场') {
                $matching_rooms[] = $room;
            }
        }
        
        // 2. 按课室选用优先级排序
        usort($matching_rooms, function($a, $b) use ($room_type) {
            if ($room_type === '学生课室') {
                // 1号楼>2号楼>3号楼>4号楼
                $priority_a = ['1' => 1, '2' => 2, '3' => 3, '4' => 4][$a['building_number']] ?? 999;
                $priority_b = ['1' => 1, '2' => 2, '3' => 3, '4' => 4][$b['building_number']] ?? 999;
            } elseif ($room_type === '电脑机房') {
                // 8号楼>4号楼>5号楼>6号楼
                $priority_a = ['8' => 1, '4' => 2, '5' => 3, '6' => 4][$a['building_number']] ?? 999;
                $priority_b = ['8' => 1, '4' => 2, '5' => 3, '6' => 4][$b['building_number']] ?? 999;
            } else {
                $priority_a = $priority_b = 1;
            }
            
            if ($priority_a !== $priority_b) {
                return $priority_a - $priority_b;
            }
            
            // 同楼栋时，低楼层>高楼层
            if ($a['floor_number'] !== $b['floor_number']) {
                return $a['floor_number'] - $b['floor_number'];
            }
            
            // 同楼层时，按课室号排序
            return strcmp($a['room_number'], $b['room_number']);
        });
        
        // 3. 选择所需数量的课室
        $selected_rooms = array_slice($matching_rooms, 0, $required_rooms);
        $room_numbers = array_map(function($room) { return $room['room_number']; }, $selected_rooms);
        
        // 4. 添加备用考场
        if ($backup_rooms > 0) {
            $backup_room_sql = "SELECT * FROM examination_rooms WHERE purpose = '备用考场' LIMIT 1";
            $backup_result = $conn->query($backup_room_sql);
            if ($backup_result->num_rows > 0) {
                $backup_room = $backup_result->fetch_assoc();
                $room_numbers[] = $backup_room['room_number'];
            }
        }
        
        echo json_encode([
            'success' => true,
            'selected_rooms' => $selected_rooms,
            'room_numbers' => $room_numbers,
            'matching_count' => count($matching_rooms)
        ]);
        exit();
    }
    
    if ($_POST['action'] === 'save_selected_rooms') {
        // 保存遴选结果
        $session_id = intval($_POST['session_id']);
        $room_numbers = $_POST['room_numbers'];
        
        $update_sql = "UPDATE arrange_examination_rooms_and_invigilators 
                      SET selected_rooms = ? 
                      WHERE exam_id = ? AND session_number = ?";
        $stmt = $conn->prepare($update_sql);
        $room_numbers_json = json_encode($room_numbers);
        $stmt->bind_param("sii", $room_numbers_json, $exam_id, $session_id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => '保存失败']);
        }
        exit();
    }
}

// 获取课室背景色函数
function getRoomBackgroundColor($room) {
    $purpose = $room['purpose'] ?? '考场';
    $room_type = $room['room_type'] ?? '未分类';

    if ($purpose == '考点办公室') {
        return '#d65e88'; // 红色
    }

    if ($purpose == '空白') {
        return '#ffffff'; // 白色
    }

    if ($purpose == '考场') {
        if ($room_type == '学生课室') {
            return '#0d6efd'; // 蓝色
        }
        if ($room_type == '实训室') {
            return '#ffc107'; // 黄色
        }
        if ($room_type == '电脑机房') {
            return '#198754'; // 绿色
        }
    }

    return '#808080'; // 灰色 - 其他情况
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编排考场及预编排监考员 - 里程碑3：遴选课室</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .milestone-nav {
            background: #f8f9fa;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
        }
        .milestone-nav a {
            text-decoration: none;
            padding: 8px 16px;
            margin: 0 5px;
            border-radius: 5px;
            background: #e9ecef;
            color: #495057;
        }
        .milestone-nav a.active {
            background: #007bff;
            color: white;
        }
        .session-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            margin-bottom: 20px;
            padding: 20px;
        }
        .room-selection-area {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-top: 15px;
        }
        .room-item {
            border: 2px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            margin: 5px;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-block;
            min-width: 80px;
            text-align: center;
        }
        .room-item:hover {
            border-color: #007bff;
            transform: scale(1.05);
        }
        .room-item.selected {
            border-color: #28a745;
            background-color: #d4edda;
        }
        .room-grid {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
        }
        .building-section {
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .selected-rooms-display {
            background: #e7f3ff;
            border: 1px solid #b3d9ff;
            border-radius: 5px;
            padding: 15px;
            margin-top: 15px;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <h2>编排考场及预编排监考员 - <?php echo htmlspecialchars($exam_name); ?></h2>
        
        <!-- 里程碑导航 -->
        <div class="milestone-nav">
            <a href="arrange_examination_rooms_milestone1.php?exam_id=<?php echo $exam_id; ?>">里程碑1：填写考场数据</a>
            <a href="arrange_examination_rooms_milestone2.php?exam_id=<?php echo $exam_id; ?>">里程碑2：计算重要数据</a>
            <a href="arrange_examination_rooms_milestone3.php?exam_id=<?php echo $exam_id; ?>" class="active">里程碑3：遴选课室</a>
            <a href="arrange_examination_rooms_milestone4.php?exam_id=<?php echo $exam_id; ?>">里程碑4：编排考场号</a>
            <a href="arrange_examination_rooms_milestone5.php?exam_id=<?php echo $exam_id; ?>">里程碑5：预编排监考员</a>
        </div>
        
        <?php if (empty($existing_data)): ?>
            <div class="alert alert-warning">
                <h5>提示</h5>
                <p>请先完成里程碑1和里程碑2的数据填写和计算。</p>
                <a href="arrange_examination_rooms_milestone1.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary">返回里程碑1</a>
            </div>
        <?php else: ?>
            <!-- 当前考试场次数据展示 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>当前考试项目场次信息</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>考试场次</th>
                                    <th>科目名称</th>
                                    <th>考试日期</th>
                                    <th>开始时间</th>
                                    <th>结束时间</th>
                                    <th>考场类型</th>
                                    <th>所需考场数</th>
                                    <th>备用考场数</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($existing_data as $index => $session): ?>
                                <tr>
                                    <td><?php echo $session['session_number']; ?></td>
                                    <td><?php echo htmlspecialchars($session['subject_name']); ?></td>
                                    <td><?php echo $session['exam_date']; ?></td>
                                    <td><?php echo $session['start_time']; ?></td>
                                    <td><?php echo $session['end_time']; ?></td>
                                    <td><?php echo $session['room_type']; ?></td>
                                    <td><?php echo $session['required_rooms']; ?></td>
                                    <td><?php echo $session['backup_rooms']; ?></td>
                                    <td>
                                        <button class="btn btn-primary btn-sm" onclick="selectRoomsForSession(<?php echo $session['session_number']; ?>)">
                                            遴选课室
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- 课室遴选区域 -->
            <div id="room-selection-area" class="room-selection-area" style="display: none;">
                <h5>课室遴选 - <span id="current-session-title"></span></h5>
                
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h6>自动遴选结果</h6>
                            </div>
                            <div class="card-body">
                                <button id="auto-select-btn" class="btn btn-success mb-3">自动遴选课室</button>
                                <div id="auto-selection-results"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h6>已选择课室</h6>
                            </div>
                            <div class="card-body">
                                <div id="selected-rooms-display" class="selected-rooms-display">
                                    <p class="text-muted">尚未选择课室</p>
                                </div>
                                <button id="save-selection-btn" class="btn btn-primary" style="display: none;" onclick="saveSelectedRooms()">保存选择</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 课室布局图 -->
                <div class="card">
                    <div class="card-header">
                        <h6>课室布局图 - 手动选择课室</h6>
                        <small class="text-muted">点击课室进行选择/取消选择</small>
                    </div>
                    <div class="card-body">
                        <div id="rooms-layout">
                            <?php
                            // 按楼栋分组显示课室
                            $rooms_by_building = [];
                            foreach ($all_rooms as $room) {
                                $building = $room['building_number'];
                                if (!isset($rooms_by_building[$building])) {
                                    $rooms_by_building[$building] = [];
                                }
                                $rooms_by_building[$building][] = $room;
                            }
                            
                            // 按楼栋号排序
                            ksort($rooms_by_building);
                            
                            foreach ($rooms_by_building as $building => $rooms):
                            ?>
                                <div class="building-section">
                                    <h6><?php echo $building; ?>号楼</h6>
                                    <div class="room-grid">
                                        <?php foreach ($rooms as $room): ?>
                                            <div class="room-item" 
                                                 data-room-id="<?php echo $room['id']; ?>"
                                                 data-room-number="<?php echo $room['room_number']; ?>"
                                                 data-room-type="<?php echo $room['room_type']; ?>"
                                                 data-purpose="<?php echo $room['purpose']; ?>"
                                                 style="background-color: <?php echo getRoomBackgroundColor($room); ?>; color: <?php echo ($room['purpose'] == '空白') ? '#333' : 'white'; ?>;"
                                                 onclick="toggleRoomSelection(this)">
                                                <div><strong><?php echo $room['room_number']; ?></strong></div>
                                                <div><small><?php echo $room['room_type']; ?></small></div>
                                                <div><small>容量: <?php echo $room['capacity']; ?></small></div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                
                <div class="mt-3">
                    <button class="btn btn-secondary" onclick="hideRoomSelection()">取消</button>
                    <button class="btn btn-success" onclick="confirmRoomSelection()">确认选择</button>
                </div>
            </div>
            
            <!-- 导航按钮 -->
            <div class="d-flex justify-content-between mt-4">
                <a href="arrange_examination_rooms_milestone2.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-secondary">上一步：计算数据</a>
                <a href="arrange_examination_rooms_milestone4.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary">下一步：编排考场号</a>
            </div>
        <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentSession = null;
        let selectedRooms = [];
        let sessionData = <?php echo json_encode($existing_data); ?>;
        
        function selectRoomsForSession(sessionNumber) {
            currentSession = sessionData.find(s => s.session_number == sessionNumber);
            if (!currentSession) {
                alert('找不到场次数据');
                return;
            }
            
            document.getElementById('current-session-title').textContent = 
                '第' + sessionNumber + '场次 - ' + currentSession.subject_name;
            
            // 重置选择
            selectedRooms = [];
            updateSelectedRoomsDisplay();
            
            // 显示遴选区域
            document.getElementById('room-selection-area').style.display = 'block';
            document.getElementById('room-selection-area').scrollIntoView({ behavior: 'smooth' });
            
            // 设置自动遴选按钮事件
            document.getElementById('auto-select-btn').onclick = function() {
                autoSelectRooms();
            };
        }
        
        function autoSelectRooms() {
            if (!currentSession) return;
            
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'select_rooms',
                    session_id: currentSession.session_number,
                    room_type: currentSession.room_type,
                    required_rooms: currentSession.required_rooms,
                    backup_rooms: currentSession.backup_rooms
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    selectedRooms = data.room_numbers;
                    
                    let html = '<h6>自动遴选完成</h6>';
                    html += '<p>符合条件的课室总数：<strong>' + data.matching_count + '</strong> 个</p>';
                    html += '<p>已选择课室：<strong>' + selectedRooms.length + '</strong> 个</p>';
                    html += '<div class="mt-2">';
                    data.selected_rooms.forEach(room => {
                        html += '<span class="badge bg-primary me-1">' + room.room_number + '</span>';
                    });
                    html += '</div>';
                    
                    document.getElementById('auto-selection-results').innerHTML = html;
                    updateSelectedRoomsDisplay();
                    highlightSelectedRooms();
                    
                    document.getElementById('save-selection-btn').style.display = 'inline-block';
                } else {
                    alert('自动遴选失败：' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('请求失败，请重试');
            });
        }
        
        function toggleRoomSelection(roomElement) {
            if (!currentSession) return;
            
            const roomNumber = roomElement.dataset.roomNumber;
            const roomType = roomElement.dataset.roomType;
            const purpose = roomElement.dataset.purpose;
            
            // 检查是否符合当前场次的课室类型要求
            if (purpose !== '考场' && purpose !== '备用考场') {
                alert('该课室不是考场，无法选择');
                return;
            }
            
            if (purpose === '考场' && roomType !== currentSession.room_type) {
                alert('该课室类型不符合要求（需要：' + currentSession.room_type + '）');
                return;
            }
            
            const index = selectedRooms.indexOf(roomNumber);
            if (index > -1) {
                // 取消选择
                selectedRooms.splice(index, 1);
                roomElement.classList.remove('selected');
            } else {
                // 检查是否超过所需数量
                const maxRooms = parseInt(currentSession.required_rooms) + parseInt(currentSession.backup_rooms);
                if (selectedRooms.length >= maxRooms) {
                    alert('已达到最大选择数量：' + maxRooms + ' 个课室');
                    return;
                }
                
                // 添加选择
                selectedRooms.push(roomNumber);
                roomElement.classList.add('selected');
            }
            
            updateSelectedRoomsDisplay();
            document.getElementById('save-selection-btn').style.display = selectedRooms.length > 0 ? 'inline-block' : 'none';
        }
        
        function updateSelectedRoomsDisplay() {
            const container = document.getElementById('selected-rooms-display');
            
            if (selectedRooms.length === 0) {
                container.innerHTML = '<p class="text-muted">尚未选择课室</p>';
                return;
            }
            
            let html = '<h6>已选择课室 (' + selectedRooms.length + '个)</h6>';
            html += '<div class="mt-2">';
            selectedRooms.forEach(roomNumber => {
                html += '<span class="badge bg-success me-1 mb-1">' + roomNumber + '</span>';
            });
            html += '</div>';
            
            if (currentSession) {
                const required = parseInt(currentSession.required_rooms);
                const backup = parseInt(currentSession.backup_rooms);
                const total = required + backup;
                
                html += '<div class="mt-2"><small class="text-muted">';
                html += '需要：' + required + '个考场';
                if (backup > 0) {
                    html += ' + ' + backup + '个备用考场';
                }
                html += ' = ' + total + '个课室</small></div>';
            }
            
            container.innerHTML = html;
        }
        
        function highlightSelectedRooms() {
            // 清除所有选择状态
            document.querySelectorAll('.room-item').forEach(item => {
                item.classList.remove('selected');
            });
            
            // 高亮显示选中的课室
            selectedRooms.forEach(roomNumber => {
                const roomElement = document.querySelector('[data-room-number="' + roomNumber + '"]');
                if (roomElement) {
                    roomElement.classList.add('selected');
                }
            });
        }
        
        function confirmRoomSelection() {
            if (selectedRooms.length === 0) {
                alert('请先选择课室');
                return;
            }
            
            if (!currentSession) {
                alert('未找到当前场次信息');
                return;
            }
            
            const required = parseInt(currentSession.required_rooms);
            const backup = parseInt(currentSession.backup_rooms);
            const total = required + backup;
            
            if (selectedRooms.length !== total) {
                if (!confirm('选择的课室数量(' + selectedRooms.length + ')与所需数量(' + total + ')不匹配，是否继续？')) {
                    return;
                }
            }
            
            saveSelectedRooms();
        }
        
        function saveSelectedRooms() {
            if (!currentSession || selectedRooms.length === 0) {
                alert('请先选择课室');
                return;
            }
            
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'save_selected_rooms',
                    session_id: currentSession.session_number,
                    room_numbers: JSON.stringify(selectedRooms)
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('课室选择已保存！');
                    hideRoomSelection();
                    // 可以在这里刷新页面或更新显示
                    location.reload();
                } else {
                    alert('保存失败：' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('保存失败，请重试');
            });
        }
        
        function hideRoomSelection() {
            document.getElementById('room-selection-area').style.display = 'none';
            currentSession = null;
            selectedRooms = [];
            
            // 清除所有选择状态
            document.querySelectorAll('.room-item').forEach(item => {
                item.classList.remove('selected');
            });
        }
    </script>
</body>
</html>